#!/bin/bash

#env java
#export JAVA_HOME=/usr/local/java/jdk1.7.0_79
#export JRE_HOME=${JAVA_HOME}/jre
#export PATH=${JAVA_HOME}/bin:$PATH

#shell 变量
bsdir="/evcharge/sc/amp"
dsdir="/evcharge/down/backup/sc"
soudir="/evcharge/down/code/sc"
codename="evcharge-sc-amp.jar"
codeback=evcharge-sc-amp
codesh="sc-amp"
date01=`date +%Y%m%d-%H%M`

function Pid2(){
pid2=$(ps aux | grep $codename | grep jar|grep -v grep |grep -v "$$"| awk '{print $2}')
}

function checkpid() {
        local i
        for i in $* ; do
                [ -d "/proc/$i" ] && return 0
        done
        return 1
}

function Status() {
    Pid2
      echo -e "\033[40;33m the $codeback server status \033[0m"
    if [ -n "${pid2}" ]; then
      echo "$codeback is running... pid:${pid2}"
      RETVAL=0
    else
      echo "$codeback is stop..."
      RETVAL=1
    fi
}

function backup() {
[ -d $dsdir/$codeback ] || mkdir -p $dsdir/$codeback
\cp -rf $bsdir $dsdir/$codeback/${codeback}_${date01}
if [ x$? == x0 ];then
echo "backup $dsdir/$codeback/${codename}_${date01} is OK"
find $dsdir/$codeback -mtime +29 |xargs rm -rf
echo "$dsdir/$codeback clean up 30 days ago"
else
echo "backup something warong"
exit 1
fi
}

function stop() {
Status
if [ -n "${pid2}" ]; then
      echo "$codeback Shutdown..."
      sh ${bsdir}/${codesh}.sh stop
      sleep 6
      checkpid ${pid2}
      if [ $?X == X ];then
        return 0
      else
        kill -9 ${pid2}
      fi
fi
sleep 1
Status
if [ x$? == x0 ];then
echo "$codeback stop"
else
echo "stop something warong"
exit 1
fi
}

function start(){
Pid2
if [ x$pid2 == x ];then
echo "$codeback is begin start"
sh ${bsdir}/${codesh}.sh start
else 
echo "$codeback start wrong, is runnging $pid2"
exit 1
fi
}

function update(){
\rm -rf $bsdir/$codeback*
\rm -rf $bsdir/lib
echo "$bsdir/* delete"
\cp -rf $soudir/* $bsdir/
if [ x$? == x0 ];then
echo "$codeback update sucess"
else 
echo "update something warong"
exit 1
fi
}

#进行判断输入变量,可提供使用2个或以上的变量输入
if [[ $# > 0 ]];then
while [ $1 ]; do
case "$1" in
    stop)
    stop
    RETVAL=$?
    ;;
    start)
    start
    RETVAL=$?
    ;;
    restart)
    stop
    start
    RETVAL=$?
    ;;
    update)
    update
    RETVAL=$?
    ;;
    status)
    Status
    RETVAL=$?
    ;;
    go)
    stop
    backup
    update
    start
    Status
    RETVAL=$?
    ;;
    *)
    echo $"Usage: $0 $codeback ps~:{start|stop|backup|update|status|go}"
    ;;
esac
#输入变量左移
shift
done
else
echo $"Usage: $0 $codeback ps~:{start|stop|backup|update|status|go}"
fi
exit $RETVAL